package com.woniu.tmsactiviti.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.tmsactiviti.entity.Cancel;
import com.woniu.tmsactiviti.entity.Compensation;
import com.woniu.tmsactiviti.entity.CustomHistory;
import com.woniu.tmsactiviti.mapper.LeaderManagerMapper;
import com.woniu.tmsactiviti.service.CompensationService;
import com.woniu.tmsactiviti.task.CustomTask;
import com.woniu.tmscommons.entity.OrderItem;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.*;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.HistoricDetailVariableInstanceUpdateEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Service
public class CompensationServiceImpl implements CompensationService {
    @Resource
    private LeaderManagerMapper leaderManagerMapper;
    @Resource
    private TaskService taskService;
    @Resource
    private HistoryService historyService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private RepositoryService repositoryService;

    @Override
    public Boolean apply(Compensation compensation) {
        //1.1 通过员工id查询到员工的组长id，及 主管id
        Integer leaderId = leaderManagerMapper.findLeaderId(compensation.getDriverId());
        Integer managerId = leaderManagerMapper.findManagerId(compensation.getDriverId());
        compensation.setLeaderId(leaderId);
        compensation.setManagerId(managerId);

        String goodsName = compensation.getGoodsName();
        BigDecimal level = compensation.getLevel();
        List<OrderItem> orderItems = compensation.getOrderItems();
        for (OrderItem item : orderItems) {
            if (goodsName.equals(item.getGoodsName())) {
                BigDecimal worth = item.getWorth();
                // 使用BigDecimal的multiply方法进行乘法运算
                BigDecimal moneyBigDecimal = worth.multiply(level);
                // 将计算的赔偿金额存入 compensation 对象中，并转换为 double
                double money = moneyBigDecimal.doubleValue();
                compensation.setMoney(money);
            }
        }

        //1.2 封装数据：流程中需要用到的变量，对象要求放在map中，流程表达式就是通过key找到变量
        Map<String, Object> args = new HashMap<>();
        args.put("compensation", compensation);

        Authentication.setAuthenticatedUserId(String.valueOf(compensation.getDriverId()));
        // 1.3 启动流程
        runtimeService.startProcessInstanceByKey("compensation", args);
        List<Task> tasks = taskService.createTaskQuery()
                .processDefinitionKey("compensation")
                .taskAssignee("" + compensation.getDriverId())
                .list();
        taskService.complete(tasks.get(tasks.size() - 1).getId());
        return true;
    }

    @Override
    public List<CustomTask> findTaskByEmpId(Integer empId) {
        // 查询当前用户的待办任务
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey("compensation")
                .taskAssignee("" + empId)
                .list();
        List<CustomTask> customTaskList = new ArrayList<>();
        // 历史查询对象
        HistoricVariableInstanceQuery query = historyService.createHistoricVariableInstanceQuery();
        for (Task task : taskList) {
            // 基本信息
            CustomTask customTask = new CustomTask(task);
            // 添加到集合
            customTaskList.add(customTask);
            // 请假详情：在流程变量中获取，通过任务id
            query.taskId(task.getId());
            // 查询
            List<HistoricVariableInstance> list = query.list();
            // 遍历
            for (HistoricVariableInstance instance : list) {
                // 获取流程变量名称
                String name = instance.getVariableName();
                // 获取流程变量值
                Object value = instance.getValue();
                // 封装
                customTask.getDetails().put(name, value);
            }
            // 计算赔偿金额
//            calculateMoney(customTask);
        }
        // 返回数据
        return customTaskList;
    }

    @Override
    public List<CustomHistory> findHistoryById(int id) {
        ObjectMapper objectMapper = new ObjectMapper();
        // System.out.println("1.开始查询历史流程");
        List<HistoricProcessInstance> list = historyService
                .createHistoricProcessInstanceQuery()
                .processDefinitionKey("compensation")
                .startedBy(String.valueOf(id))
                .list();
        // 创建list保存所有记录
        List<CustomHistory> customHistories = new ArrayList<>();
        // 遍历
        // System.out.println("================遍历流程实例================start");
        list.forEach(processInstance -> {
            // 创建流程对象
            CustomHistory customHistory = new CustomHistory();
            // 获取流程id
            String processInstanceId = processInstance.getId();
            // 设置流程id
            customHistory.setId(processInstanceId);

            // System.out.println("2.通过流程id查询流程实例，判断是否结束");
            ProcessInstance instance = runtimeService
                    .createProcessInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .singleResult();

            // 判断
            customHistory.setFinished(instance == null ? true : false);

            // System.out.println("3.根据流程id查询任务列表");
            List<HistoricTaskInstance> taskInstances = historyService.createHistoricTaskInstanceQuery()
                    .processInstanceId(processInstanceId)
                    .orderByHistoricTaskInstanceStartTime().asc()
                    .list();
            // System.out.println("----------------遍历历史任务----------------start");
            taskInstances.forEach(taskInstance -> {
                // 创建任务对象，封装数据
                CustomTask customTask = new CustomTask(taskInstance);

                // System.out.println("4.根据任务id查询任务详情");
                List<HistoricDetail> details = historyService
                        .createHistoricDetailQuery()
                        .taskId(taskInstance.getId())
                        .list();
                // 遍历
                // System.out.println("................遍历任务详情信息.................start");
                details.forEach(detail -> {
                    HistoricDetailVariableInstanceUpdateEntity entity =
                            (HistoricDetailVariableInstanceUpdateEntity) detail;
                    // 获取详情信息
                    String name = entity.getName();
                    String textValue = entity.getTextValue();
                    // 获取值的类型
                    String type = entity.getTextValue2();

                    // 根据类型创建对象
                    try {
                        Class<?> clazz = Class.forName(type);
                        Object obj = objectMapper.readValue(textValue, clazz);
                        // 封装到详情中
                        customTask.getDetails().put(name, obj);
                    } catch (Exception e) {
                        customTask.getDetails().put(name, textValue);
                    }
                    // 判断之前有任务id与现在相同，就不放进去
                    boolean flag = true;
                    for (CustomTask task : customHistory.getCustomTaskList()) {
                        if (task.getId().equals(customTask.getId())) {
                            flag = false;
                        }
                    }
                    if (flag) {
                        customHistory.getCustomTaskList().add(customTask);
                    }
                });
                // 计算赔偿金额
//                calculateMoney(customTask);
            });
            customHistories.add(customHistory);
        });
        return customHistories;
    }

    @Override
    public Boolean cancel(Cancel cancel) {
        // 参数1：流程id
        // 参数2：撤销原因
        runtimeService.deleteProcessInstance(cancel.getPid(), cancel.getReason());
        return true;
    }


    @Override
    public Boolean completeTask(String taskId, boolean agree) {
        List<Task> subTasks = taskService.getSubTasks(taskId);
        for (Task task : subTasks){
            System.out.println(task);
        }
        // 设置流程变量
        taskService.setVariableLocal(taskId, "auditResult", agree ? "Y" : "N");
        // 完成任务
        taskService.complete(taskId);
        return true;
    }

    @Override
    public List<Map<String, Object>> getProcessStatus(List<CustomHistory> customHistory, String processInstanceId) {
        List<Map<String, Object>> statusList = new ArrayList<>();
        // 遍历 CustomHistory
        for (CustomHistory history : customHistory) {
            // 检查 processInstanceId 是否匹配
            if (history.getId().equals(processInstanceId)) {
                List<CustomTask> customTaskList = history.getCustomTaskList();
                for (CustomTask task : customTaskList) {
                    // 创建流程步骤的映射
                    Map<String, Object> step = new HashMap<>();
                    step.put("name", task.getName());
                    step.put("timestamp", task.getEndTime() != null ? task.getEndTime() : task.getStartTime());
                    step.put("completed", task.getEndTime() != null);
                    step.put("agreeResult", task.getDetails().get("auditResult")); // 根据你存储的结果字段名来获取
                    statusList.add(step);
                }
                break; // 找到对应的 processInstanceId 后结束循环
            }
        }

        return statusList;
    }
}
